var dbUtils = angular.module("dbUtils",[]);

dbUtils.factory("dbUtils", ["$http", "$window","$q","toaster","$modal", DbFetch]);

    function DbFetch($http, $window,$q,toaster,$modal) {
        var promise = false;
        var deferred = $q.defer();

        function getHtml(content, type) {
            var html = [];
            html.push('<div class="modal-header">');
            html.push('<h3 class="modal-title">提示</h3>');
            html.push('</div>');
            html.push('<div class="modal-body">');
            html.push(content);
            html.push('</div>');
            html.push('<div class="modal-footer">');
            html.push('<button class="btn btn-primary" type="button" ng-click="ok()">确定</button>');
            if (type == "confirm") {
                html.push('<button class="btn btn-warning" type="button" ng-click="cancel()">取消</button>');
            }
            html.push('</div>');
            return html.join('');
        }

        function DialogController($scope, $modalInstance) {
            $scope.ok = function () {
                $modalInstance.close('cancel');
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            }
        }

        function dbAlert(content, okFun) {
            $modal.open({
                animation: true,
                template: getHtml(content),
                controller: ['$scope', '$modalInstance', DialogController],
                size: "sm",
                backdrop: "static"
            }).result.then(function () {
                if (angular.isFunction(okFun)) {
                    okFun.call();
                }
            });
        }

        function doTip(content) {
            var html = [];
            html.push('<div class="modal-header">');
            html.push('<h3 class="modal-title">提示</h3>');
            html.push('<div class="modal-body">');
            html.push(content);
            html.push('</div>');
            html.push('</div>');
            html.push('<div class="modal-footer">');
            html.push('</div>');

            $modal.open({
                animation: true,
                template: html.join(""),
                controller: ['$scope', '$modalInstance', DialogController],
                size: "sm"
            })
        }

        function doToasterTip(type, title, content) {
            toaster.pop({
                type: type,
                title: title,
                body: content,
                timeout: 4000,
                bodyOutputType: 'trustedHtml'
            });
        }

        return {
            success: function (content, title) {
                doToasterTip('success', title, content);
            },
            info: function (content, title) {
                doToasterTip('info', title, content);
            },
            warning: function (content, title) {
                doToasterTip('warning', title, content);
            },
            error: function (content, title) {
                doToasterTip('error', title, content);
            },
            alert: function (content, okFun) {
                dbAlert(content, okFun);
            },
            tip: function (content) {
                doToasterTip(content);
            },
            confirm: function (content, okFun, cancerFun) {
                $modal.open({
                    animation: true,
                    template: getHtml(content, 'confirm'),
                    controller: ['$scope', '$modalInstance', DialogController],
                    size: "sm",
                    backdrop: "static"
                }).result.then(function () {
                    okFun.call();
                }, function () {
                    if (angular.isFunction(cancerFun)) {
                        cancerFun.call();
                    }
                });
            },
            post: function (transCode, reqBody, success, error) {

                var ApiRequest = {};
                ApiRequest["transCode"] = transCode;
                ApiRequest["requestBody"] = reqBody;

                if(!promise){
                    promise = deferred.promise;
                }

                // var apiUrl = "http://hp.xiqing.info/mobile/api.do";
                // var apiUrl = "http://localhost:8080/mobile/api.do";
                $http.post(transCode, ApiRequest).success(function (data, status, headers, config) {

                    if(data['status']===200) {
                        success(data.responseBody);
                    }else if (data['status']===500){
                        // $.dialog({
                        //     content : "加载数据失败，请稍后再试！",
                        //     title: null,
                        //     time : 2000
                        // });
                        console.log("网络通讯异常，请稍后再试！");
                    }else{
                        // $.dialog({
                        //     content : "网络通讯异常，请稍后再试！",
                        //     title: null,
                        //     time : 2000
                        // });
                        console.log("网络通讯异常，请稍后再试！");
                    }
                    deferred.resolve(data);
                    //判断返回值是系统异常，还是业务异常，来决定是否需要调用error回调
                }).error(function (data, status, headers, config) {

                    // $.dialog({
                    //     content : "网络通讯异常，请稍后再试！",
                    //     title: null,
                    //     time : 2000
                    // });

                    console.log("网络通讯异常，请稍后再试！");

                    deferred.reject();
                });

                return deferred.promise;

            },
            get: function (transCode, reqBody,success,error) {
                var ApiRequest = {};
                ApiRequest["transCode"] = transCode;
                ApiRequest["requestBody"] = reqBody;

                if(!promise){
                    promise = deferred.promise;
                }

                $http.get(transCode, ApiRequest).success(function (data) {

                    success(data.responseBody);
                    deferred.resolve(data);

                    //判断返回值是系统异常，还是业务异常，来决定是否需要调用error回调
                }).error(function (data, status, headers, config) {
                    error(data);

                    deferred.reject();

                });

                return deferred.promise;
            },
            dateFormat: function (date) {
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                var date = date.getDate();
                return year + "-" + (month > 9 ? month : ("0" + month)) + "-" + (date > 9 ? date : ("0" + date));
            },

            /*
             * 根据指定变量获取集合中此变量的数组数据返回.
             * @param name
             * @param rows
             * @returns {Array}
             */
            getFieldArray: function (objectList, name) {
                var data = [];
                angular.forEach(objectList, function (record) {
                    data.push(record[name]);
                });
                return data;
            }
        }
    }